$(function () {
    // 判断是否登陆
    var username = getCookie('username')
    if(username){
        $('.customNav').html(`
        <li style="color:#999">
            欢迎:<span style="color:red;">${username}</span>
        </li>
        <li>
            <a href="javascript:;" class="logout">退出</a>
        </li>
        `)
        $('.logout').click(function(){
            removeCookie('username');
            localStorage.setItem('data',[]);
            $('.customNav').html(`
            <li>
                <a href="javascript:;">登录</a>
            </li>
            <li>
                <a href="register.html">注册</a>
            </li>
            `)
            gologin()
        })
        
        
    }else{
        layer.msg('请先登录！',{
            icon:2,
            time:1500
        },function(){
            localStorage.setItem('url',location.href)
            location.href = "login.html";
        })
    }
    // 购物车数据
    var data = localStorage.getItem('data');
    var nn=0;
    // console.log(data);
     if(!data || data==='[]'){
        $('#productList').html(`
            <div class="jumbotron">
            <img src="../image/shop-cart.JPG" style="margin: 0 auto;"> 
        </div>
        `) 
        $('#settlement').html(``);
    }else{
         // 有数据
         var arr = JSON.parse(data);
         var ids = arr.map(item=>item.goodsid).join(',')
         // console.log(ids);
         console.log(ids);
         var str='';
         $.get('../php/cart.php',{ids},res=>{
            var {meta:{status,msg},data} = JSON.parse(res);
            
            if(status===1){
                 str = `
                 <div id="title">
                <div><h3>全部商品&nbsp;&nbsp;<span id="num">0</span>
                </h3>
                </div>
                <div class="address">
                    <span>配送至：</span>
                    <div class="jdarea">
                        <div class="ui-area"><div class="ui-area-text">广东深圳市宝安区新安街道
                        </div>
                        <b></b>
                    </div>
                    </div>
                   
                </div>
            </div>
            <div class="cart-thead">
                <div class="column t-checkbox">
                    <div class="cart-checkbox">
                        <input type="checkbox" name="select-all" class="jdcheckbox" >
                    </div>
                    全选
                </div>
                    <div class="column t-goods">商品

                    </div>
                    <div class="column t-props">&nbsp;

                    </div>
                    <div class="column t-price">单价

                    </div>

                    <div class="column t-quantity">数量

                    </div>
                    <div class="column t-sum">小计
                    </div>
                    <div class="column t-action">操作

                    </div>
                </div>`;
                // console.log(data);
                var s=0;
                var arr2=[];
                data.forEach(item=>{
                   // 如果找到这个商品
                    var obj =arr.find(v=>v.goodsid==item.id)
                    arr2.push(item);
                    arr2[arr2.length-1].num=obj.number
                    // item[num]=obj.number;
                })
                // 获取正常
                var shop='';
                var string2=[];
                var j=0;
                if(arr2!=''){
                 arr2.forEach(item=>{
                     j++;
                   shop=item.shopName;
                       var sum=item.pirce*item.num;
                       nn++;
                       str+=`
                       <div class="shop-list">
              <div class="shop-title">
                  <input type="checkbox" class="checkBox">
                  <span class="shop-name">${item.shopName}</span>
                  <i></i>
                  <div class="shop-yhj">优惠卷</div>
              </div>
              <div class="shop-content">
                  <div class="shopContent-sum">
                      <span class="decount">满减</span>
                      <span class="shopdecount-tip">满两件总价9折</span>
                      <span class="shopdecount-cd">去凑单</span>
                      
                  </div>
                  <div class="sum-price">
                      <p></p>
                  </div>
                  <div class="shopContent-list">
                      <input type="checkbox" class="contentlist-check">
                      <div class="item-form">
                          <div class="goods-detail" number="${item.id}">
                              <img src="${item.image}.jpg">
                          <div class="goods-name">
                              <div class="shangbiao">
                                  <img src="../image/京东自营.png">
                              </div>
                              <a href="javascript:;" style="color:black;">${item.name}</a>
                          </div>
                         
  
                          </div> 
                          <div class="goodsName-detail">
                              <p>${item.description}</p>
  
                          </div> 
                          <div class="goods-price">
                              <p>¥${item.pirce}</p>
                              <span>促销</span>
                          </div>
                          
                          <div class="cart-number quantity ">
                              <button class="cart-number-dec is-disabled" disabled="">
                                  <i class="cart-icon-subt">-
                                  </i>
                              </button>
                              <div class="cart-input">
                                  <input class="cart-input-o" min="1" max="200" value="${item.num}">
                              </div>
                              <button class="cart-number-inc">
                                  <span class="cart-icon-add">+
                                  </span>
                              </button>
                              <p>有货</p>
                          </div>
  
                          <div class="cell p-sum">
                              <strong>¥${sum}
                              </strong>
                          </div>
  
  
                          <div class="cell p-ops">
                              <a href="#none" class="p-ops-item">删除
  
                              </a>
                              <!-- <a href="#none" class="p-ops-item">移入关注
  
                              </a> -->
                          </div>
  
  
                      </div>
                      </div>
                  </div>
  
              </div>
                       `
                       string2.push(shop);
                       // 判断是否还有同店铺的
                       for(var i=j;i<arr2.length;i++){
                           if(string2.indexOf(arr2[i].shopName)>-1){
                               nn++;
                               str+=`
                               <div class="shop-content">
                <div class="shopContent-sum">
                    <span class="decount">满减</span>
                    <span class="shopdecount-tip">满两件总价9折</span>
                    <span class="shopdecount-cd">去凑单</span>
                    

                </div>
                <div class="sum-price">
                    <p></p>
                </div>
                <div class="shopContent-list">
                    <input type="checkbox" class="contentlist-check">
                    <div class="item-form">
                        <div class="goods-detail" number="${item.id}">
                            <img src="${arr2[i].image}.jpg">
                        <div class="goods-name">
                            <div class="shangbiao">
                                <img src="../image/京东自营.png">
                            </div>
                            <a href="#" style="color:black;">${arr2[i].name}</a>
                        </div>
                       

                        </div> 
                        <div class="goodsName-detail">
                            <p>${arr2[i].description}</p>

                        </div> 
                        <div class="goods-price">
                            <p>¥${arr2[i].pirce}</p>
                            <span>促销</span>
                        </div>
                        
                        <div class="cart-number quantity ">
                            <button class="cart-number-dec is-disabled" disabled="">
                                <i class="cart-icon-subt">-
                                </i>
                            </button>
                            <div class="cart-input">
                                <input class="cart-input-o" min="1" max="200" value="${arr2[i].num}">
                            </div>
                            <button class="cart-number-inc">
                                <span class="cart-icon-add">+
                                </span>
                            </button>
                            <p>有货</p>
                        </div>

                        <div class="cell p-sum">
                            <strong>¥${sum}
                            </strong>
                        </div>


                        <div class="cell p-ops">
                            <a href="#none" class="p-ops-item">删除

                            </a>
                            <!-- <a href="#none" class="p-ops-item">移入关注

                            </a> -->
                        </div>


                    </div>
                    </div>
                </div>
                               `
                                    arr2.splice(i,1);
                           }

                       }
                })
                $('#productList').html(str);
                $('#num').html(nn);
            }

             //全选功能
    $('.jdcheckbox').on('click', selectAll);
    $('#settlement [type="checkbox"]').on('click', selectAll);
    // 店铺全选
    $('.checkBox').on('click', selectshopAll);
    // 每次点击多选框都计算总价并查看店铺是否需要全选
    $('[type="checkbox"]').on("click", seleCount);
    $('.cart-number-dec').prop('disabled', false);
    // 数量减框
    $('.cart-number-dec').on('click', reduce);
    // 数量加框
    $('.cart-number-inc').on('click', add);
    // 删除购物车中的商品
    $('.p-ops-item').on('click', dele);
               }
       })
       
         
    }
    //全选功能
    $('.jdcheckbox').on('click', selectAll);
    $('#settlement [type="checkbox"]').on('click', selectAll);
    // 店铺全选
    $('.checkBox').on('click', selectshopAll);
    // 每次点击多选框都计算总价并查看店铺是否需要全选
    $('[type="checkbox"]').on("click", seleCount);
    $('.cart-number-dec').prop('disabled', false);
    // 数量减框
    $('.cart-number-dec').on('click', reduce);
    // 数量加框
    $('.cart-number-inc').on('click', add);
    // 删除购物车中的商品
    $('.p-ops-item').on('click', dele);
})

// 减数量
function reduce() {
    var num = $(this).siblings().first().children('.cart-input-o').val() - 0;
    if (num > 1) {
        num--;
        $(this).siblings().first().children('.cart-input-o').attr('value', num);
    } else {
        layer.msg("已经不能再少啦", {
            icon: 1,
            time: 1500,
        }, function () {})
    }
    num = $(this).siblings().first().children('.cart-input-o').val() - 0;
    countsum(this, num);
    count();
}
// 移除数组中的元素
function removeArrayAll(arr,value){
    var i=0;
    while(i<arr.length){
        if(arr[i].shopName==value){
            arr.splice(i,1);
        }else{
            ++i;
        }
        return arr;
    }
}
    
// 加数量
function add() {
    var num = $(this).siblings().eq(1).children('.cart-input-o').val() - 0;
    if (num < 20) {
        num++;
        $(this).siblings().eq(1).children('.cart-input-o').attr('value', num);
    } else {
        layer.msg("已经不能再加啦", {
            icon: 1,
            time: 1500,
        }, function () {})
    }
    num = $(this).siblings().eq(1).children('.cart-input-o').val() - 0;
    countsum(this, num)
    count();
}
// 删除整个list;
function dele() {
    // 首先判断该店铺是否只有一个商品在购物车
    var num = $(this).parent().parent().parent().parent().siblings('.shop-content').length - 0;
    // 如果大于则存在，不用删除店铺，
    if (num > 0) {
        $(this).parent().parent().parent().parent().remove();
        count();

    } else {
        $(this).parent().parent().parent().parent().parent().remove();
        count();
    }
    // 删除本地缓存中的数据
    var data3 = localStorage.getItem('data');
    var sss=JSON.parse(data3);
    var goodsid=$(this).parent().siblings().eq(0).attr('number');
    console.log(goodsid);
    var index = sss.findIndex(item=>item.goodsid == goodsid)
    sss.splice(index,1)
     localStorage.setItem('data',JSON.stringify(sss));
     $('#num').html(sss.length);
    if ($('.shop-list').length == 0) {
        // 购物车里空空如也
        $('#productList').html(`
        <div class="jumbotron">
        <img src="../image/shop-cart.JPG" style="margin: 0 auto;"> 
    </div>
    `) 
    $('#settlement').html(``);
    }

}

// 加减完计算每件商品的总价 
function countsum(that, number) {
    // 加减完需要算该行的总费用
    var p = $(that).parent().siblings().eq(2).children('p');
    var price = $(p).text().split('¥')[1] - 0;
    //  var num2=$(that).siblings().first().children('.cart-input-o').val()-0;
    var sum = price * number;
    $(that).parent().siblings().eq(3).children('strong').html('¥' + sum + '.00')
}
// 全选功能
function selectAll() {
    $('[type="checkbox"]').prop('checked', $(this).prop('checked'))
}
// 店内全选
function selectshopAll() {
    $(this).parent().siblings().eq(0).children().eq(2).children().prop('checked', $(this).prop('checked'));

    if ($('.checkBox:checked').length == $('.checkBox').length) {
        $('[type="checkbox"]').prop('checked', true);
    } else {
        $('.jdcheckbox').prop('checked', false);
        $('.checkAll').prop('checked', false)
    }

}

function seleCount() {
    // 查看店铺是否需要选中
    // 店铺商品个数
    var num = $(this).parent().parent().parent().children('.shop-content').length - 0;
    // 如果个数和其相等
    if (num == $(this).parent().parent().parent().children('.shop-content').children('.shopContent-list').children('.contentlist-check:checked').length) {
        $(this).parent().parent().parent().children().first().children().first().prop('checked', $(this).prop('checked'));
        if ($('.checkBox:checked').length == $('.checkBox').length) {
            $('[type="checkbox"]').prop('checked', true);
        } else {
            $('.jdcheckbox').prop('checked', false);
            $('.checkAll').prop('checked', false)
        }
    } else if (num > $(this).parent().parent().parent().children('.shop-content').children('.shopContent-list').children('.contentlist-check:checked').length) {
        // 店铺取消全选
        $(this).parent().parent().parent().children().first().children().first().prop('checked', false);
        // 全选框也取消
        $('.jdcheckbox').prop('checked', false);
        $('.checkAll').prop('checked', false)

    }
    if ($(this).parent().parent().parent().children('.shop-content').children('.shopContent-list').children('.contentlist-check:checked').length < $('[type="checkbox"]').length - 2)
        // 计算总价
        count();

}
// 计算总价
function count() {
    var price = 0;
    //选择选中的多选框
    $('.shopContent-list .contentlist-check:checked').each((i, v) => {
        // 获取小计里面的数据
        var s = $(v).siblings('.item-form').children()[4];
        price += $(s).text().split('¥')[1] - 0;
    })
    // 将价格放在标签中
    console.log(price);
    sumPrice(price);
}
//将计算出来的总价放在标签中
function sumPrice(price) {
    var num = $('.contentlist-check:checked').length - 0;
    $('#totalNum').html(num);
    $('#totalPrice').html(price);
}
//登陆点击shijian
function gologin(){
    $('.customNav li:first a').click(function(){
        // 点击登录
        // 跳转之前先设置一个本地存储将当前url存起来
        localStorage.setItem('url',location.href)
        // 需要跳转到登录页
        location.href = "login.html";
        // 登录成功后需要跳回来
    })
}
